import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { request } from "src/request";
import { MixIngredient } from "./useMixIngredients";
import { BaseIngredient } from "./useBaseIngredients";

export type Formula = {
  id?: string;
  rate?: number;
  mid?: string;
  bid?: string;
  remark?: string;
  mixIngredient?: MixIngredient;
  baseIngredient?: BaseIngredient;
}

export function useFormulas(mixIngredientId): [Formula[], Dispatch<SetStateAction<Formula[]>>, () => Promise<void>, boolean] {
  const [formulas, setFormulas] = useState<Formula[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchFormulas = async () => {
    setLoading(true);
    try {
      const response = await request.get(`/mix-ingredient/${mixIngredientId}/formulas`);
      setFormulas(response.data as Formula[]);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchFormulas();
  }, []);

  return [formulas, setFormulas, fetchFormulas, loading];
}

export async function saveFormulas(mixIngredientId, formulas) {
  const response = await request.post(`/mix-ingredient/${mixIngredientId}/formulas`, formulas);
  return response.data;
}
